package com.qnzw.zjmy.ad.kaku;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.Request;
import com.anythink.core.api.ATAdConst;
import com.anythink.core.api.ATAdInfo;
import com.anythink.core.api.ATShowConfig;
import com.anythink.core.api.AdError;
import com.anythink.rewardvideo.api.ATRewardVideoAd;
import com.anythink.rewardvideo.api.ATRewardVideoListener;
import com.google.gson.Gson;
import com.qnzw.zjmy.BuildConfig;
import com.qnzw.zjmy.ad.inter.RewardAdCallbackInter;
import com.qnzw.zjmy.config.UrlAddressConfig;
import com.qnzw.zjmy.config.UrlConfig;
import com.qnzw.zjmy.home.ui.model.vo.AdRecordSa;
import com.qnzw.zjmy.home.ui.model.vo.AdRecordVo;
import com.qnzw.zjmy.home.ui.model.vo.UserDailyActivityVo;
import com.qnzw.zjmy.utils.risk.DeviceUtils;
import com.qnzw.zjmy.utils.risk.RiskUtils;
import com.qnzw.zjmy.utils.risk.VirtualApkCheckUtil;
import com.qnzw.zjmy.volley.BaseFragment;
import com.qnzw.zjmy.volley.state.HUCState;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 激励视频
 */
public class TaKuRewardAdCallback implements ATRewardVideoListener {
    private static String TAG = "TaKuRewardAdCallback";

    private ATRewardVideoAd mRewardVideoAd;
    private String transId;
    private String userId;
    private String token;
    private String returnOrderId;
    private String orderId;
    private BaseFragment baseFragment;
    private AlertDialog alertDialog;
    private RewardAdCallbackInter rewardAdCallbackInter;
    private Activity activity;
    private String placementId;
    private static volatile TaKuRewardAdCallback instance;

    private boolean flag = false;

    private TaKuRewardAdCallback() {
    }

    public static synchronized TaKuRewardAdCallback getInstance() {
        if (ObjectUtil.isNull(instance)) {
            synchronized (TaKuRewardAdCallback.class) {
                if (ObjectUtil.isNull(instance)) {
                    instance = new TaKuRewardAdCallback();
                }
            }
        }
        return instance;
    }

    public void loadAd(Context context, String placementId) {
        this.placementId = placementId;
        mRewardVideoAd = new ATRewardVideoAd(context, placementId);
        randomOrderId();
        if (ObjectUtil.isNotNull(activity)) {
            mRewardVideoAd.setAdListener(this);
        }
        mRewardVideoAd.load();
    }

    public void showAd(Activity activity) {
        this.activity = activity;
        if (ObjectUtil.isNull(mRewardVideoAd)) {
            flag = true;
            loadAd(activity.getApplicationContext(), placementId);
            return;
        }
        if (mRewardVideoAd.isAdReady()) {
            if (alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            mRewardVideoAd.setAdListener(this);
            mRewardVideoAd.show(activity, getATShowConfig());
        } else {
            //重新加载
            randomOrderId();
            mRewardVideoAd.setAdListener(this);
            flag = true;
            mRewardVideoAd.load();
        }
    }

    @Override
    public void onRewardedVideoAdLoaded() {
        if (ObjectUtil.isNotNull(activity) && flag) {
            if (alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            mRewardVideoAd.show(activity, getATShowConfig());
            flag = false;
        }
    }

    @Override
    public void onRewardedVideoAdFailed(AdError adError) {
        Log.e(TAG, "onRewardedVideoAdFailed:" + adError.getFullErrorInfo());
        if (ObjectUtil.isNotNull(activity) && flag) {
            if (alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            Toast.makeText(baseFragment.getActivity(), "视频加载失败", Toast.LENGTH_LONG).show();
        }
    }
    private static long AD_DISPLAY_DURATION = 15000; // 设定广告停留的最小时间，单位为毫秒
    private Date adStartTime;  // 记录广告的开始时间
    private Date adEndTime;  // 记录广告的结束时间
    private boolean isAdClosed = false;  // 标记广告是否关闭
    private Handler handler = new Handler();

    // 停留时间
    private String answeringTime;
    // 答题奖励判断类型 1 taku 2自然人
    private String answerType;

    @Override
    public void onRewardedVideoAdPlayStart(ATAdInfo atAdInfo) {
        Log.e(TAG, "onRewardedVideoAdFailed:" + atAdInfo.getAdNetworkType());
        if (ObjectUtil.isNotNull(atAdInfo)) {

            //判断类型
            if(answerType.equals("2")){

                try {
                    isAdClosed = false;
                    handler = new Handler();

                    AD_DISPLAY_DURATION = Long.parseLong(answeringTime);
                    Log.e(TAG, "广告停留需求打印--------转换成功，值为: " +AD_DISPLAY_DURATION);
                    // 记录广告开始时间
//                    adStartTime = System.currentTimeMillis();
                    adStartTime = new Date();  // 获取当前时间

                    Log.e(TAG, "广告停留需求打印--------记录广告开始时间: " +adStartTime);

                    // 设定一个定时器，达到停留时间后执行上报
                    handler.postDelayed(() -> {
                        if (!isAdClosed) {
                            // 如果广告还没有关闭，且已到达停留时间，则直接上报
                            adEndTime = new Date();  // 获取当前时间
                            Log.e(TAG, "广告停留需求打印--------记录广告结束时间: " +adEndTime);
                            reportAdData(atAdInfo,adStartTime,adEndTime);
                        }
                    }, AD_DISPLAY_DURATION);

                } catch (NumberFormatException e) {
                    Log.e(TAG, "广告停留需求打印--------无效的数字格式");
                }

            }


            Double ecpm = atAdInfo.getPublisherRevenue(); //展示广告的价格 0.105234661721
            ecpm = ecpm * 100000;
            int firmId = atAdInfo.getNetworkFirmId();  //展示广告的adn名称
            String sdkName = "other";
            switch (firmId) {
                case 28://快手
                    sdkName = "ks";
                    break;
                case 8://腾讯广告(优量汇)
                    sdkName = "gdt";
                    break;
                case 15://穿山甲（CSJ）
                    sdkName = "pangle";
                    break;
                default: //其他
                    break;
            }

            String slotId = atAdInfo.getNetworkPlacementId(); //展示广告的代码位ID
            AdRecordVo adRecordVo = new AdRecordVo();
            adRecordVo.setArTransId(orderId);
            adRecordVo.setEcpm(String.valueOf(ecpm.intValue()));
            adRecordVo.setToken(token);
            adRecordVo.setArChannel(sdkName);
            adRecordVo.setArMediationRit(slotId);
            //采集数据
            //是否分身
            boolean flag = VirtualApkCheckUtil.getSingleInstance().checkByCreateLocalServerSocket(DeviceUtils.getInstance().getPackageName(Objects.requireNonNull(baseFragment.getActivity())));
            adRecordVo.setUdaSeparation(String.valueOf(flag ? 1 : 2));
            //是否模拟器
            flag = RiskUtils.getInstance().detectEmulator(baseFragment.getActivity());
            adRecordVo.setUdaSimulator(String.valueOf(flag ? 1 : 2));
            //是否开启调试模式
            flag = DeviceUtils.getInstance().isDeveloperModeEnabled(baseFragment.getActivity());
            adRecordVo.setUdaDebugMode(String.valueOf(flag ? 1 : 2));
            //是否USB调试模式
            flag = DeviceUtils.getInstance().isAdbEnabled(baseFragment.getActivity());
            adRecordVo.setUdaUsbMode(String.valueOf(flag ? 1 : 2));
            //是否root
            flag = DeviceUtils.getInstance().isDeviceRooted(baseFragment.getActivity());
            adRecordVo.setUdaRoot(String.valueOf(flag ? 1 : 2));
            //是否开启无障碍模式
            flag = DeviceUtils.getInstance().isAccessibilityServiceEnabled(baseFragment.getActivity());
            adRecordVo.setUdaAccessibility(String.valueOf(flag ? 1 : 2));
            //是否开启VPN代理模式
            flag = DeviceUtils.getInstance().isWifiProxy();
            adRecordVo.setUdaVpnProxy(String.valueOf(flag ? 1 : 2));

            String simOperator = DeviceUtils.getInstance().getNetworkOperatorName(baseFragment.getActivity());
            Log.e(TAG, "SIM运营商--------"+simOperator);
            //SIM运营商
            adRecordVo.setUdaSimOperator(simOperator);
            Log.e(TAG, "SIM运营商--------"+simOperator);
            //悬浮窗状态
            adRecordVo.setSystemAlertWindow(DeviceUtils.getInstance().getSystemAlertWindow(baseFragment.getActivity()));
            //蓝牙状态
            adRecordVo.setOpenBluetooth(DeviceUtils.getInstance().getOpenBluetooth(baseFragment.getActivity()));

            if(UrlAddressConfig.CHANNEL_TYPE!=1){
                adRecordVo.setUdaSeparation(String.valueOf(2));
                //是否模拟器
                adRecordVo.setUdaSimulator(String.valueOf(2));
                //是否开启调试模式
                adRecordVo.setUdaDebugMode(String.valueOf(2));
                //是否USB调试模式
                adRecordVo.setUdaUsbMode(String.valueOf(2));
                //是否root
                adRecordVo.setUdaRoot(String.valueOf(2));
                //是否开启无障碍模式
                adRecordVo.setUdaAccessibility(String.valueOf(2));
                //是否开启VPN代理模式
                adRecordVo.setUdaVpnProxy(String.valueOf(2));
            }

            //手机应用总数
            List<PackageInfo> packageInfoList = DeviceUtils.getInstance().getAllApps(baseFragment.getActivity());
            adRecordVo.setUdaAllApp(String.valueOf(ObjectUtil.isNotEmpty(packageInfoList) ? packageInfoList.size() : 0));
            List<UserDailyActivityVo> userDailyActivityVoList = new ArrayList<>();
            for (PackageInfo packageInfo : packageInfoList) {
                UserDailyActivityVo userDailyActivityVo = new UserDailyActivityVo();
                String name = DeviceUtils.getInstance().getAppName(baseFragment.getActivity(), packageInfo.packageName);
                userDailyActivityVo.setUdaPackage(packageInfo.packageName);
                userDailyActivityVo.setUdaAppName(name);
                userDailyActivityVo.setUdaVersionCode(packageInfo.versionName);
                userDailyActivityVoList.add(userDailyActivityVo);
            }
            Gson gson = new Gson();
            // 将 User 对象转换为 JSON 字符串
            String jsonString = gson.toJson(userDailyActivityVoList);
            //应用JSON明细
            adRecordVo.setUdaAllAppDetail(jsonString);
            baseFragment.hucRequestInterfase.executeStr(baseFragment, null, HUCState.HUC_REQEUST_CODE_5, Request.Method.POST, UrlConfig.URL_AD_RECORD, baseFragment.hucParameInterfase.getRequestParameter(adRecordVo), true);
        }
        //建议在此回调中调用load进行广告的加载，方便下一次广告的展示（不需要调用isAdReady()）
        returnOrderId = orderId;
        randomOrderId();
        mRewardVideoAd.load();
    }


    // 上报广告数据
    private void reportAdData(ATAdInfo atAdInfo, Date rocordStartTime, Date rocordEndTime) {
        if (atAdInfo != null) {

            int firmId = atAdInfo.getNetworkFirmId();  // 获取广告网络的 ID
            String sdkName = "other";

            // 判断广告来源
            switch (firmId) {
                case 28:
                    sdkName = "ks";  // 快手
                    break;
                case 8:
                    sdkName = "gdt";  // 腾讯广告
                    break;
                case 15:
                    sdkName = "pangle";  // 穿山甲广告
                    break;
                default:
                    break;
            }

            // 获取广告位 ID
            String slotId = atAdInfo.getNetworkPlacementId();

            // 创建广告记录对象
            AdRecordSa adRecordVo = new AdRecordSa();
            adRecordVo.setArTransId(orderId);
            adRecordVo.setUvChannel(BuildConfig.CHANNEL_PACKAGE);
            adRecordVo.setToken(token);
            adRecordVo.setArChannel(sdkName);
            adRecordVo.setArMediationRit(slotId);
            adRecordVo.setRocordStartTime(rocordStartTime);
            adRecordVo.setRocordEndTime(rocordEndTime);

            // 上报广告数据
            Log.e(TAG, "广告停留需求打印--------上报广告地址接口: " +UrlConfig.URL_AD_RECORD_SAVE);
            Log.e(TAG, "广告停留需求打印--------上报广告数据: " +baseFragment.hucParameInterfase.getRequestParameter(adRecordVo));
            baseFragment.hucRequestInterfase.executeStr(baseFragment, null, HUCState.HUC_REQEUST_CODE_5,
                    Request.Method.POST, UrlConfig.URL_AD_RECORD_SAVE,
                    baseFragment.hucParameInterfase.getRequestParameter(adRecordVo), true);
        }
    }


    public void setAnsweringTime(String answeringTime) {
        this.answeringTime = answeringTime;
    }



    public void setAnswerType(String answerType) {
        this.answerType = answerType;
    }



    @Override
    public void onRewardedVideoAdPlayEnd(ATAdInfo atAdInfo) {
    }

    @Override
    public void onRewardedVideoAdPlayFailed(AdError adError, ATAdInfo atAdInfo) {
    }

    @Override
    public void onRewardedVideoAdClosed(ATAdInfo atAdInfo) {
        Log.e(TAG, "onRewardedVideoAdClosed: Ad has been closed");
        // 广告关闭时，标记广告已关闭
        isAdClosed = true;

        // 取消定时器，如果广告已在播放时就达到了停留时间，不再上报
        handler.removeCallbacksAndMessages(null);
        Log.e(TAG, "广告停留需求打印--------广告关闭 ，不再上报");

        rewardAdCallbackInter.rewardAdCallback(returnOrderId);
    }

    @Override
    public void onRewardedVideoAdPlayClicked(ATAdInfo atAdInfo) {
        Log.e(TAG, "onRewardedVideoAdPlayClicked:" + atAdInfo.getAdNetworkType());
    }

    @Override
    public void onReward(ATAdInfo atAdInfo) {
        Log.e(TAG, "onReward:" + atAdInfo.getAdNetworkType());
    }

    private void randomOrderId() {
        orderId = UUID.randomUUID().toString().replace("-", "");
        Map<String, Object> localMap = new HashMap<>();
        localMap.put(ATAdConst.KEY.USER_ID, userId);
        localMap.put(ATAdConst.KEY.USER_CUSTOM_DATA, orderId);
        mRewardVideoAd.setLocalExtra(localMap);
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public void setBaseFragment(BaseFragment baseFragment) {
        this.baseFragment = baseFragment;
    }

    public void setRewardAdCallbackInter(RewardAdCallbackInter rewardAdCallbackInter) {
        this.rewardAdCallbackInter = rewardAdCallbackInter;
    }

    public void setAlertDialog(AlertDialog alertDialog) {
        this.alertDialog = alertDialog;
    }

    private ATShowConfig getATShowConfig() {
        orderId = UUID.randomUUID().toString().replace("-", "");
        ATShowConfig.Builder builder = new ATShowConfig.Builder();
        builder.scenarioId(userId);
        builder.showCustomExt(orderId + StrUtil.COMMA + BuildConfig.CHANNEL_PACKAGE);
        return builder.build();
    }
}
